<template>
    <!-- <div class="b-title d-flex align-center justify-space-between">
        <div class="b-word d-flex align-center">
            链上聪明钱<img class="b-img" width="20" height="20" src="@/assets/Star.png"/>
        </div>
        <div class="b-right d-flex align-center">
            更多<img class="r-img" width="20" height="20" src="@/assets/more.png"/>
        </div>
    </div> -->
    <div class="j-row">
        <div v-for="(item, idx) in list" class="j-col" :key="idx">
            <div class="r-bank d-flex align-center c-title-2">
                <img :src="getAvatar(item.name)" class="c-img" />
                <span class="c-name c-title-3" @click="() => toBrowser(item)">{{ item.name }}</span>
                <span class="mdi mdi-earth" @click="onJump(item.website)"></span>
                <span class="mdi mdi-twitter" @click="onJump(item.twitter)"></span>
                <!-- <JShare>
                    <span class="mdi mdi-share-variant"></span>
                </JShare> -->
                <JShare>
                    <span class="iconfont icon-2102fenxiang md-share"></span>
                </JShare>
            </div>
            <div class="r-coin d-flex align-center justify-space-between">
                <!-- <div class="r-txt">0xf97…41acee</div> -->
                <span class="c-title-4">
                    <!-- 资产分布情况 -->
                    {{ $t("message.Clever.a") }}
                </span>
                <div class="coin-list">
                    <img :src="i" class="coin-img" v-for="i in item.imgs" />
                </div>
            </div>
            <div class="c-list c-title-5">
                <div class="c-item" v-for="(i, idx) in item.items" :key="idx">
                    <div class="top1 text-truncate" @click="onToken(i)">
                        <v-tooltip location="top start">
                            <template v-slot:activator="{ props }">
                                <span v-bind="props">{{ i.name }}</span>
                            </template>
                            <Tip :item="i" :show="true"></Tip>
                        </v-tooltip>
                    </div>

                    <!-- <div class="top1 text-truncate" @click="onToken(i)" @mouseover="onEnter(i)" @mouseout="onOut">{{
                        i.name }}</div> -->
                    <div class="top2">
                        <JNumber :amin="false" :num="i.usd" prefix="$"></JNumber>
                    </div>
                </div>
            </div>
            <div class="r-comm d-flex align-center justify-space-between">
                <span class="c-left c-title-4">
                    <!-- 总余额 -->
                    {{ $t("message.Clever.b") }}
                </span>
                <span class="c-title-5">
                    <!-- <span class="c-title-4" style="font-weight: 700;"></span> -->
                    <JNumber class="c-title-4" :amin="false" :num="formatBigNumber(item.totalUsd) as unknown as any"></JNumber>&nbsp;
                    <JNumber :amin="false" :num="item.totalUsd - item.preTotalUsd" :is-color="true"></JNumber>
                    <!-- <span :class="[item.totalUsd - item.preTotalUsd > 0 ? 'win-color' : 'lose-color']"> {{formatBigNumber(item.totalUsd - item.preTotalUsd)}}</span> -->
                </span>
            </div>

            <div class="r-comm d-flex align-center justify-space-between">
                <span class="c-left c-title-4">
                    <!-- 7天餘額變化 -->
                    {{ $t("message.Clever.c") }}
                </span>
                <span class="c-right c-change c-title-5">
                    <!-- <Arrow :up="true" :size="14" txt="23%"></Arrow> -->
                    <!-- <img src="~@/assets/vue.svg" class="coin-up"/>
                    <span class="greens">+23%</span> -->
                    <JNumber :amin="false" :num="item.totalUsd - item.pre7DayUsd" :is-color="true" :is-arrow="true"></JNumber>
                    <!-- <span class="change-txt" :class="[item.totalUsd - item.pre30DayUsd > 0 ? 'win-color' : 'lose-color']">{{formatBigNumber(item.totalUsd - item.pre30DayUsd)}}</span> -->
                    <!-- <span class="iconfont icon-arrow_down" :class="{up: item.totalUsd - item.pre30DayUsd > 0}"></span> -->
                </span>
            </div>

            <div class="r-comm d-flex align-center justify-space-between">
                <span class="c-left c-title-4">
                    <!-- 最後活跃 -->
                    {{ $t("message.Clever.d") }}
                </span>
                <!-- <span class="c-title-5"> {{ formatTimeAgo(item.lastChangToken.time.value) }} {{item.lastChangToken.symbol}} ${{formatBigNumber(item.lastChangToken.usd)}}</span> -->
                <span class="c-title-4"> {{ formatTimeAgo(item.lastChangTime) }}</span>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { URL_AVATAR, URL_TOKEN_DATA } from "@/comm/api";
import { onMounted, computed, ref } from "vue";
import { useRouter } from "vue-router";
import { formatBigNumber, formatTimeAgo } from "@/comm/format";
import { get } from "@/comm/request";
import Arrow from "@/components/arrow2/index.vue";
import Copy from "@/components/copy/index.vue";
import JNumber from "@/components/j-number/index.vue";
import { useAccount } from "@/stores/account";
import { useClever } from "@/stores/clever";
import { useTokens } from "@/stores/tokens";
import JShare from "@/components/j-share/index.vue";
import Tip from "./tip.vue";
import i18n from "@/locals";
import { Bus, CONN_CHAIN_CLEVER } from "@/connetion/Bus";
import { uuidCreate } from "@/comm/uuid";
import { sortList } from "@/comm/tooler";

const account = useAccount();

const clever = useClever();
const tokens = useTokens();

const curTip = ref(null);

const onEnter = (obj: any) => {
    // console.log("on enter")
    curTip.value = obj;
    // console.log("on enter", curTip.value)
};

const onOut = () => {
    // console.log("on out")
    curTip.value = null;
};

onMounted(() => {
    clever.init();
    Bus.on(CONN_CHAIN_CLEVER, data => {
        if (Array.isArray(data)) {
            data.forEach(i => {
                clever.updateData(i);
            });
        } else {
            clever.updateData(data);
        }
    });
});

const getAvatar = (str: string) => {
    return URL_AVATAR.replace("@", str);
};

const onToken = async (item: any) => {
    // console.log('yzt',item)
    if (!item.link) {
        // console.log("yzt沒有鏈上數據");
        return;
    }
    // router.push({ name: 'token', params: { id: item.link } });
    window.open("/token/" + item.link);
    // let res: any = await get(URL_TOKEN_DATA, { token: item.link });
    // console.log(res);
};

interface Item {
    name: string;
    id: string;
    capitalInfoId: string;
}

const router = useRouter();
const toBrowser = function (item: Item) {
    console.log(item);
    // router.push("entity/hello");
    // router.push({ name: 'entity', params: { a: 100 } });
    // localStorage.setItem("coin", JSON.stringify({ name: item.name, id: item.capitalInfoId }))
    // router.push({ path: 'entity', query: { name: item.name, id: item.capitalInfoId } });
    // router.push({name: 'entity', params: {id: item.capitalInfoId}})
    window.open("/entity/" + item.capitalInfoId);
};

const onJump = (url: string) => {
    console.log(url, list);
    window.open(url);
};

const onShare = () => {
    let twitter = "https://twitter.com/intent/tweet?url=" + encodeURIComponent(location.origin) + "&text=" + encodeURIComponent("well done!");
    let facebook = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(location.origin) + "&t=" + encodeURIComponent("well done!");
    console.log(twitter);
    console.log(facebook);
    // window.open(facebook);
    account.changePopShare(true);
};

const list = computed(() => {
    // console.log(clever.clevers, "clever.clevers ====");

    if (!clever.clevers) return [];
    let ary = clever.clevers.slice(0, 4);
    let temp = ary.map(i => {
        let items;
        if (!i.blockBalanceList) {
            i.blockBalanceList = [];
        }
        let max = Math.min(i.blockBalanceList.length, 4);
        let imgs = [];
        for (let t = 0; t < max; t++) {
            // console.log("ddddddddd", i.blockBalanceList[t]);
            let img = tokens.getImg(i.blockBalanceList[t].symbol);
            imgs.push(img);
        }
        i.imgs = imgs;

        let totalBalance = [...i.blockBalanceList].reduce((a, b) => (a += b.balance), 0);
        // console.log("totalUsd", totalUsd)
        if (i.blockBalanceList.length > 4) {
            let total = 0;
            let balance = 0;
            items = i.blockBalanceList.slice(0, 4).map((val: any) => {
                let percent = (val.usd / i.totalUsd) * 100;
                total += percent;
                balance += val.balance;
                return {
                    name: val.symbol,
                    percent: percent.toFixed(1) + "%",
                    link: val.contractAddress,
                    balance: val.balance,
                    usd: val.usd,
                    id: val.id
                    // key: uuidCreate()
                };
            });
            // items.push({
            //     // name: "其他",
            //     name: i18n.global.t('message.Clever.e'),
            //     percent: (100 - total).toFixed(1) + "%",
            //     usd: i.totalUsd - total,
            //     balance: totalBalance - balance
            // })
        } else {
            items = i.blockBalanceList.map((val: any) => {
                let percent = 0;
                if (i.totalUsd == 0 && val.usd == 0) {
                    percent = 100;
                } else {
                    percent = (val.usd / i.totalUsd) * 100;
                }
                return {
                    name: val.symbol,
                    percent: percent.toFixed(1) + "%",
                    link: val.contractAddress,
                    balance: val.balance,
                    usd: val.usd,
                    id: val.id
                    // key: uuidCreate()
                };
            });
        }

        // console.log("items", items)

        return {
            ...i,
            items
        };
    });

    sortList(temp, "lastChangTime");

    return temp;
});
</script>

<style lang="less" scoped>
@import url("./index.less");
</style>
